#include "seriesinstance.h"
#include "imageinstance.h"

SeriesInstance::SeriesInstance():
    rawPtr(0)
{
}

SeriesInstance::~SeriesInstance()
{
    qDeleteAll(imageMap.values());
}

bool SeriesInstance::insertImage(ImageInstance *image)
{
    if (image && seriesNum.isEmpty()) {
        seriesNum = image->seriesNumber;
    }
    if (image && (!image->seriesNumber.isEmpty())&& image->seriesNumber==seriesNum) {
        imageMap.insert(image->instanceNumber.toInt(), image);
        return true;
    }
    return false;
}

bool SeriesInstance::hasImage(const QString &file)
{
    foreach (ImageInstance *image, imageMap.values()) {
        if (image->filePath == file) return true;
    }
    return false;
}

int SeriesInstance::getSeriesNumber() const
{
    if (!imageMap.isEmpty()) return imageMap.first()->seriesNumber.toInt();
    else return -1;
}

QString SeriesInstance::getPatientName() const
{
    return imageMap.isEmpty()?QString():imageMap.first()->patientName;
}

QString SeriesInstance::getModality() const
{
    return imageMap.isEmpty()?QString():imageMap.first()->modality;
}

QImage SeriesInstance::getInstancePixmap(int slice)
{
    return (imageMap.isEmpty()||slice>=imageMap.size())?QImage():imageMap.values().at(slice)->getPixmap();
}

const short *SeriesInstance::getInstanceInterData(int slice)
{
    return (imageMap.isEmpty()||slice>=imageMap.size())?0:imageMap.values().at(slice)->getInterData();
}

bool SeriesInstance::getPixelSpacing(double &px, double &py, int slice) const
{
    return (imageMap.isEmpty()||slice>=imageMap.size())?false:imageMap.values().at(slice)->getPixelSpacing(px, py);
}

const ushort **SeriesInstance::getRawVolume(const ushort **&volume, ulong &width, ulong &height, ulong &slice)
{
    volume = 0;
    if (imageMap.isEmpty()) return volume;

    delete[] rawPtr;
    ulong rawSlice = imageMap.values().size();
    rawPtr = new const ushort*[rawSlice];
    ImageInstance *image;
    for (int i = 0; i < rawSlice; ++i) {
        image = imageMap.values().at(i);
        rawPtr[i] = image->getRawData();
    }

    volume = rawPtr;
    imageMap.first()->getImageSize(width, height);
    slice = rawSlice;
    return volume;
}
